package com.ant.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LB
 */
public class TreeCodeUtil {

    public final static String PARENT_CODE = "0001";
    public final static String FIRST_CODE = "0001";

    /**
     * true:公平锁；false：非公平锁，就是独占锁
     */
    private final static Lock lock = new ReentrantLock(true);

    public static String getTreeCode(String maxCode, String parentCode) {
        lock.lock();
        try {
            if (StringUtils.isEmpty(parentCode)) {
                return PARENT_CODE;
            }

            if (StringUtils.isEmpty(maxCode)) {
                return parentCode + FIRST_CODE;
            }

            //只截取需要+1的部分（将 parentCode 去掉）
            String oldCode = maxCode.substring(parentCode.length(), maxCode.length());
            //先将最大的code变成int
            long code = Long.parseLong(oldCode) + 1;
            //得到新的 code 之后将 parentCode 加上
            return parentCode + StringUtils.leftPad(String.valueOf(code), oldCode.length(), "0");
        } finally {
            lock.unlock();
        }
    }
}
